package com.test.platform.viewmodel

import PublishInfoRepository
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.test.platform.model.PublishInfo
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class PublishInfoViewModel(
    private val repository: PublishInfoRepository = PublishInfoRepository()
) : ViewModel() {
    private val _publishInfos = MutableStateFlow<List<PublishInfo>>(emptyList())
    val publishInfos: StateFlow<List<PublishInfo>> = _publishInfos.asStateFlow()
    
    private val _loading = MutableStateFlow(false)
    val loading: StateFlow<Boolean> = _loading.asStateFlow()
    
    private val _error = MutableStateFlow<String?>(null)
    val error: StateFlow<String?> = _error.asStateFlow()
    
    fun loadPublishInfos() {
        viewModelScope.launch(Dispatchers.IO) {
            _loading.value = true
            try {
                val result = repository.getPublishInfos()
                withContext(Dispatchers.Main) {
                    _publishInfos.value = result
                    _error.value = null
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    _error.value = e.message ?: "加载失败"
                }
            } finally {
                withContext(Dispatchers.Main) {
                    _loading.value = false
                }
            }
        }
    }
}